import useResizeObserver from '@/hook/useResizeObserver'
import * as echarts from 'echarts'
import { PropsWithChildren, useEffect, useRef, useState } from 'react'
interface AutoChartProps {
  className?: string
  option: echarts.EChartsOption
}

export default function AigcEchart(params: PropsWithChildren<AutoChartProps>) {
  const chartRef = useRef<any>()

  const [chart, setChart] = useState<echarts.ECharts>()
  const dimensions = useResizeObserver(chartRef)
  const handleResize = () => chart?.resize()

  const init = () => {
    // if (chart) {
    //   // 建议替换为 ResizeObserver（2023.5.25）
    //   window.removeEventListener('resize', handleResize)
    // }
    if (chart) {
      chart.dispose()
    }

    const _chart: echarts.ECharts = echarts.init(
      chartRef.current as any as HTMLElement
    )

    _chart.setOption(params.option)
    if (chart) {
      handleResize()
    }

    // window.addEventListener('resize', handleResize)
    setChart(_chart)
  }

  useEffect(() => {
    init()
    // console.log('reRender')
    return () => {}
  }, [params.option, dimensions])

  return (
    <div
      className={params.className}
      ref={chartRef}
      style={{ width: '100%' }}
    ></div>
  )
}
